# coding=utf-8

from application import app, redis
from common.libs.JsonLibs import bytes_to_obj
from app.model.mysql.game_category import GameCategory as GameCategoryMysql
from app.model.redis.game_category import GameCategory as GameCategoryRedis
from app.json.mysql.game_category import GameCategory as GameCategoryJson


def get_one(gc_id):
    redis_gc_one = redis.get(GameCategoryRedis.game_category_one.key % gc_id)
    if redis_gc_one:
        mysql_gc_one = None
    else :
        mysql_gc_one = GameCategoryMysql.query.filter(GameCategoryMysql.id == gc_id, GameCategoryMysql.is_delete == 0).first()
    if mysql_gc_one:
        setInRedis(mysql_gc_one)
        gc_json = GameCategoryJson(mysql_gc_one).getJson()
    else :
        gc_json = bytes_to_obj(redis_gc_one)
    return gc_json


def get_list():
    redis_gc_set = redis.smembers(GameCategoryRedis.game_category_one.key)
    redis_gc_list = list(redis_gc_set)
    redis_gc_list = redis_gc_list if redis_gc_list else []
    result_list = []
    if not redis_gc_list:
        mysql_gc_list = GameCategoryMysql.query.filter(GameCategoryMysql.is_delete == 0).all()
        for mysql_gc_one in mysql_gc_list:
            setInRedis(mysql_gc_one)
            gc_one_json = GameCategoryJson(mysql_gc_one).getJson()
            result_list.append(gc_one_json)
        return result_list
    else:
        for gc_id in redis_gc_list:
            gc_one_json = get_one(gc_id.decode("utf-8"))
            result_list.append(gc_one_json)
        return result_list


def setInRedis(mysql_gc_one):
    redis.sadd(GameCategoryRedis.game_category_set.key, mysql_gc_one.id)
    redis.set(GameCategoryRedis.game_category_one.key % mysql_gc_one.id, GameCategoryJson(mysql_gc_one).getJsonToRedis())
